package yunjiao.javatutorials.lang.concurrent.interrupt;

/**
 * 长时间运行任务的优雅中断
 *
 * @author yangyunjiao
 */
public class LongRunningTaskExample {
    public static void main(String[] args) throws InterruptedException {
        Thread longTask = new Thread(new LongRunningTask());
        longTask.start();

        // 让任务运行3秒后中断
        Thread.sleep(1000);
        longTask.interrupt();
        System.out.println("发送中断信号给长时间运行任务");
    }

    static class LongRunningTask implements Runnable {
        @Override
        public void run() {
            int count = 0;
            // 定期检查中断状态
            while (!Thread.currentThread().isInterrupted()) {
                // 模拟长时间计算
                for (int i = 0; i < 1000000; i++) {
                    // 在计算密集型任务中定期检查中断
                    if (i % 1000 == 0 && Thread.currentThread().isInterrupted()) {
                        System.out.println("检测到中断信号，准备退出");
                        return;
                    }
                    Math.sqrt(i); // 模拟计算
                }
                System.out.println("完成第 " + (++count) + " 轮计算");
            }
            System.out.println("长时间运行任务优雅结束");
        }
    }
}
